<template>
  <div class="contact-management">
    <div class="page-header">
      <h1>联系我们管理</h1>
      <div class="header-stats">
        <el-tag type="danger" size="large">未读: {{ stats.unread }}</el-tag>
        <el-tag type="warning" size="large">已读: {{ stats.read }}</el-tag>
        <el-tag type="success" size="large">已回复: {{ stats.replied }}</el-tag>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.status" placeholder="筛选状态" clearable @change="handleFilterChange">
            <el-option label="全部" value="" />
            <el-option label="未读" value="unread" />
            <el-option label="已读" value="read" />
            <el-option label="已回复" value="replied" />
            <el-option label="已归档" value="archived" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input
            v-model="filters.search"
            placeholder="搜索姓名、邮箱、主题或内容"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </el-col>
        <el-col :span="4">
          <el-dropdown @command="handleBatchAction">
            <el-button :disabled="selectedIds.length === 0">
              批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="read">标记为已读</el-dropdown-item>
                <el-dropdown-item command="archived">归档</el-dropdown-item>
                <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表单列表 -->
    <el-card>
      <el-table
        :data="contacts"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              size="small"
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="phone" label="电话" width="150" />
        
        <el-table-column label="主题" width="200">
          <template #default="scope">
            {{ scope.row.subject || '无主题' }}
          </template>
        </el-table-column>
        
        <el-table-column label="消息内容" min-width="300">
          <template #default="scope">
            <div class="message-content">
              {{ scope.row.message }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="语言" width="80">
          <template #default="scope">
            <el-tag size="small" type="info">
              {{ getLanguageName(scope.row.language) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="提交时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewContact(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              @click="replyContact(scope.row)"
              :disabled="scope.row.status === 'replied'"
            >
              回复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="联系表单详情"
      width="600px"
    >
      <div v-if="currentContact" class="contact-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentContact.status)">
              {{ getStatusText(currentContact.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="姓名">{{ currentContact.name }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentContact.email }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ currentContact.phone || '未提供' }}</el-descriptions-item>
          <el-descriptions-item label="主题">{{ currentContact.subject || '无主题' }}</el-descriptions-item>
          <el-descriptions-item label="语言">{{ getLanguageName(currentContact.language) }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatTime(currentContact.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentContact.ipAddress || '未记录' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="message-section">
          <h4>消息内容：</h4>
          <div class="message-text">{{ currentContact.message }}</div>
        </div>
        
        <div v-if="currentContact.replyContent" class="reply-section">
          <h4>回复内容：</h4>
          <div class="reply-text">{{ currentContact.replyContent }}</div>
          <p class="reply-time">回复时间：{{ formatTime(currentContact.repliedAt!) }}</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="viewDialogVisible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="replyContact(currentContact!)"
          :disabled="currentContact?.status === 'replied'"
        >
          回复
        </el-button>
      </template>
    </el-dialog>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复联系表单"
      width="600px"
    >
      <div v-if="replyingContact" class="reply-form">
        <div class="contact-info">
          <p><strong>联系人：</strong>{{ replyingContact.name }} ({{ replyingContact.email }})</p>
          <p><strong>主题：</strong>{{ replyingContact.subject || '无主题' }}</p>
          <div class="original-message">
            <h4>原始消息：</h4>
            <p>{{ replyingContact.message }}</p>
          </div>
        </div>
        
        <el-form :model="replyForm" :rules="replyRules" ref="replyFormRef">
          <el-form-item label="回复内容" prop="content">
            <el-input
              v-model="replyForm.content"
              type="textarea"
              :rows="6"
              placeholder="请输入回复内容"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="replyDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          :loading="replying" 
          @click="submitReply"
        >
          发送回复
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { request } from '../../utils/request'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Contact {
  id: number
  name: string
  email: string
  phone?: string
  subject?: string
  message: string
  language: string
  status: string
  ipAddress?: string
  userAgent?: string
  createdAt: string
  repliedAt?: string
  replyContent?: string
}

interface ContactStats {
  total: number
  unread: number
  read: number
  replied: number
  archived: number
}

const contacts = ref<Contact[]>([])
const loading = ref(false)
const selectedIds = ref<number[]>([])
const viewDialogVisible = ref(false)
const replyDialogVisible = ref(false)
const currentContact = ref<Contact | null>(null)
const replyingContact = ref<Contact | null>(null)
const replying = ref(false)
const replyFormRef = ref<FormInstance>()

const stats = ref<ContactStats>({
  total: 0,
  unread: 0,
  read: 0,
  replied: 0,
  archived: 0
})

const filters = reactive({
  status: '',
  search: ''
})

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

const replyForm = reactive({
  content: ''
})

const replyRules: FormRules = {
  content: [
    { required: true, message: '请输入回复内容', trigger: 'blur' }
  ]
}

const getContacts = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams({
      page: pagination.page.toString(),
      pageSize: pagination.pageSize.toString(),
      ...filters
    })

    const response = await request.get(`/contact/list?${params}`)
    if (response.success) {
      contacts.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取联系表单列表失败')
  } finally {
    loading.value = false
  }
}

const getStats = async () => {
  try {
    const response = await request.get('/contact/stats/overview')
    if (response.success) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

const refreshData = () => {
  getContacts()
  getStats()
}

const handleFilterChange = () => {
  pagination.page = 1
  getContacts()
}

const handleSearch = () => {
  pagination.page = 1
  getContacts()
}

const handlePageChange = () => {
  getContacts()
}

const handlePageSizeChange = () => {
  pagination.page = 1
  getContacts()
}

const handleSelectionChange = (selection: Contact[]) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleBatchAction = async (command: string) => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要操作的表单')
    return
  }

  try {
    let confirmText = ''
    let successText = ''
    
    switch (command) {
      case 'read':
        confirmText = `确定要将选中的 ${selectedIds.value.length} 条表单标记为已读吗？`
        successText = '标记成功'
        break
      case 'archived':
        confirmText = `确定要将选中的 ${selectedIds.value.length} 条表单归档吗？`
        successText = '归档成功'
        break
      case 'delete':
        confirmText = `确定要删除选中的 ${selectedIds.value.length} 条表单吗？删除后无法恢复！`
        successText = '删除成功'
        break
    }

    await ElMessageBox.confirm(confirmText, '批量操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    let response
    if (command === 'delete') {
      response = await request.delete('/contact/batch/delete', {
        data: { ids: selectedIds.value }
      })
    } else {
      response = await request.put('/contact/batch/status', {
        ids: selectedIds.value,
        status: command
      })
    }

    if (response.success) {
      ElMessage.success(successText)
      selectedIds.value = []
      refreshData()
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const viewContact = async (contact: Contact) => {
  try {
    const response = await request.get(`/contact/${contact.id}`)
    if (response.success) {
      currentContact.value = response.data
      viewDialogVisible.value = true
      // 刷新列表以更新状态
      getContacts()
      getStats()
    }
  } catch (error) {
    ElMessage.error('获取详情失败')
  }
}

const replyContact = (contact: Contact) => {
  replyingContact.value = contact
  replyForm.content = ''
  replyDialogVisible.value = true
  viewDialogVisible.value = false
}

const submitReply = async () => {
  if (!replyFormRef.value || !replyingContact.value) return

  await replyFormRef.value.validate(async (valid) => {
    if (valid) {
      replying.value = true
      try {
        const response = await request.post(`/contact/${replyingContact.value!.id}/reply`, {
          replyContent: replyForm.content
        })

        if (response.success) {
          ElMessage.success('回复成功')
          replyDialogVisible.value = false
          refreshData()
        }
      } catch (error) {
        ElMessage.error('回复失败')
      } finally {
        replying.value = false
      }
    }
  })
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'unread': return 'danger'
    case 'read': return 'warning'
    case 'replied': return 'success'
    case 'archived': return 'info'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'unread': return '未读'
    case 'read': return '已读'
    case 'replied': return '已回复'
    case 'archived': return '已归档'
    default: return '未知'
  }
}

const getLanguageName = (lang: string) => {
  switch (lang) {
    case 'en': return '英语'
    case 'es': return '西语'
    case 'ja': return '日语'
    default: return lang?.toUpperCase() || '未知'
  }
}

const formatTime = (time: string) => {
  return new Date(time).toLocaleString('zh-CN')
}

onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.contact-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}

.header-stats {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.message-content {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.contact-detail {
  margin-bottom: 20px;
}

.message-section,
.reply-section {
  margin-top: 20px;
}

.message-section h4,
.reply-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.message-text,
.reply-text {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.reply-time {
  margin: 10px 0 0 0;
  color: #909399;
  font-size: 12px;
}

.reply-form {
  margin-bottom: 20px;
}

.contact-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.contact-info p {
  margin: 5px 0;
  color: #606266;
}

.original-message {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

.original-message h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
}

.original-message p {
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  margin: 0;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>